<?php
namespace Lib\Controller;
//use Lib\Controller\AppController;
use Think\Controller;
use Home\Logic\WxloginLogic;
class HomeBaseController extends Controller{

    private $wxLoginLogic;
    private $UserModel;
    private $AccessTokenModel;
    public function __construct() {
        $this->wxLoginLogic = new WxloginLogic();
        $this->UserModel = D('User');
        $this->AccessTokenModel = D('wx_access_token');
        if(cookie('wx_access_token')==null){
            $this->_getWXAccessToken();
        }
        if(ACTION_NAME != 'test'){
        
       
            if(cookie('userinfo')==null){
                session('userinfo',null);
                $this->_checkWxLogin();
            }
         }
        $this->clearImg(); //清理空间
        parent::__construct();
    }

    /**
     * [clearImg 定时清理空间]
     * @author xiezy
     * @date   2017-09-28
     * @return [type]     [description]
     */
    private function clearImg(){
        //判断上个月的今天
        $lastMonthDay = date('Ymd',strtotime("-1 month"));
        //上个月的今天拍摄的图片地址
        $car_img = './Upload/car_img/'.$lastMonthDay;
        if ( file_exists($car_img) ) {
            //触发删除目录及文件
            static::delDirAndFile($car_img);
        }
    }

    /**
     * [getCoupon 获取用户的优惠卷]
     * @author xiezy
     * @date   2017-10-19
     * @param  [type]     $get_type  0=>分享 , 1=>注册
     * @return [type]
     */
    public function getUserCoupon($get_type){
        $where['get_type'] = $get_type;          // 0=>分享 , 1=>注册
        $where['end_time'] = array('gt',time()); //结束时间大于现在时间
        $couponList = M('coupon')->where($where)->select();
        foreach($couponList as$key=>$val){
            // $coupondata['server_id'] = -1;                        //通用
            $coupondata['member_id'] = cookie('userinfo')['id'];  //用户id
            $coupondata['coupon_id'] = $val['id'];                //优惠卷类型id
            // $coupondata['status']    = 1;

            M('userCoupon')->add($coupondata);
        }
    }

    /**
     * [delDirAndFile 循环删除目录和文件函数]
     * @author xiezy
     * @date   2017-09-28
     *         删除该目录和目录下的文件
     * @param  [type]     $dirName [目录名]
     * @return [type]              [description]
     */
    private static function delDirAndFile( $dirName )
    {
        if ( $handle = opendir( "$dirName" ) ) {
            while ( false !== ( $item = readdir( $handle ) ) ) {
                if ( $item != "." && $item != ".." ) {
                    if ( is_dir( "$dirName/$item" ) ) {
                        delDirAndFile( "$dirName/$item" );
                    } else {
                        @unlink( "$dirName/$item" ) ; //删除文件
                    }
                }
            }
            closedir( $handle );//关闭目录
            @rmdir( $dirName );  //删除目录
        }
    }

    public function _checkWxLogin(){
        $code = I("get.code");

        $userInfo = cookie('userinfo');
        if(!$userInfo['id'] && !$code){
            $this->_wxLogin();
        }
    }
    private function _wxLogin(){
        $redirect_uri = 'https://washcar.zhfancon.com/index/getUserInfo';
        $this->wxLoginLogic->login($redirect_uri);
    }

    private function _getWXAccessToken(){
        $findAccessToken = $this->AccessTokenModel->order('id desc')->find();
        if(!empty($findAccessToken) && $findAccessToken['expires_time'] < time() || empty($findAccessToken)){
            $this->wxLoginLogic->getAccessToken();

            $accessTokenData['wx_access_token'] = cookie("wx_access_token");
            $accessTokenData['create_time'] = time();
            $accessTokenData['expires_time'] = time()+7000;
            $addNewAccessToken = $this->AccessTokenModel->add($accessTokenData);
        }
        else if(!empty($findAccessToken) && $findAccessToken['expires_time'] > time()){
            $token['access_token'] = $findAccessToken['wx_access_token'];
            $expireTime = $findAccessToken['expires_time'] - time();
            cookie('wx_access_token',$token["access_token"],$expireTime);
        }
    }

    /**
     * @param num $status 状态 0 1
     * @param string $info 操作信息
     * @param string $url 跳转路径
     * @param array $array 返回数组
     * @param string $type 回调格式 'JSON' 默认
     */
    function tmAjaxReturn($status, $info = '', $url = '', $array = array(), $type = 'JSON') {
        $data ['status'] = $status; // 状态
        $data ['info'] = $info; // 提示信息
        $data ['url'] = $url; // 跳转地址
        $data ['data'] = $array; // 返回数据

        $this->ajaxReturn($data, $type);
    }

    function wxCurlPost($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }
    /**
     * 查重openid
     * @param unknown $openid
     * @return unknown
     */
    function checkOpenid($openid,$type="user"){
        $where['openid'] = $openid;
        if($type=='user'){
            $result = $this->UserModel->find_uesr($where,$type="find");
        }
        else if($type=='server'){
            $result = D('server')->where($where)->find();
        }

        if($result){
            $this->checkOpenid(date('YmdHis',time()).rand(1000000,9999999));
        }else{
            return $openid;
        }
    }
    /**
     * 推送微信消息模板
     * @param array $userInfo 用户信息
     * @param array $pushdata 模板数据data
     * @param array $templateid 模板id
     * @param array $color 头标题颜色
     * @param array $data
     */
    public function pushWXMessage($userInfo,$pushdata,$templateid,$orderurl=''){
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".cookie('wx_access_token');

        //封装模板数据
        $pushdata = array(
            'touser' => $userInfo['weixin_openid'],
            'template_id' => $templateid,
            'url' => $orderurl,
            'topcolor' => '#FF0000', //红色
            'data' => $pushdata
        );


        $json_pushdata = json_encode($pushdata);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, urldecode($json_pushdata));
        $output = curl_exec($ch);
        curl_close($ch);

        $pushResult = json_decode($output,true);
        if($pushResult['errcode'] == '-1'){
            $this->pushWXMessage($userInfo, $pushdata,$templateid,$orderurl='');
        }
    }

}

?>
